import React, { useEffect, useRef, useState } from 'react';
import type { RadioChangeEvent } from 'antd';
import { Button, Card, Checkbox, DatePicker, Form, Input, Radio, message } from 'antd';
import LostCardTable from './LostCardTable';
import moment from 'moment';
import useWebSocket from '@/hooks/UseWebsocket';
import dayjs from 'dayjs';
import { AddlsockLog, delLostCard } from './request';
import AdminCardmodel from '../HourCard/components/AdminCardmodel';
import { getLogLossCardCardNum } from '@/pages/account/Business/service';
import { LostTimer } from '../ManageCards/request';
import { useDetermineCardType } from '@/hooks/DetermineCardType';
import { useIntl } from '@umijs/max';
import { Read_Card, Write_LossCard } from '@/utils/Send';
const index: React.FC = () => {
  const [value, setValue] = useState('');
  const [checkIntimer] = useState(moment().add(7, 'days'));
  const [excludeNumber2] = useState([]);
  const [sendMsg, setsendMsg] = useState(''); // 发送消息
  const [CardMessage, setCardMessage] = useState(); // 接受消息
  const [type, setType] = useState<string>(''); // 成功后的提示消息
  const [form] = Form.useForm();
  const intl = useIntl();
  // const [_, sendMessage, lastMessage, isConnected] = useWebSocket({
  //   url: 'ws://127.0.0.1:9909',
  //   onOpen: () => {
  //     if (sendMsg) {
  //       sendMessage(sendMsg);
  //     }
  //   },
  //   onClose: () => {
  //     //连接关闭
  //     console.log('WebSocket disconnected');
  //   },
  //   onError: (event) => {
  //     //连接异常
  //     console.error('WebSocket error:', event);
  //   },
  //   onMessage: (onmsg) => {
  //     //收到消
  //     setCardMessage(JSON.parse(onmsg));
  //     // console.log(JSON.parse(onmsg))
  //   },
  // });

  // useEffect(() => {
  //   if (isConnected && sendMsg) {
  //     sendMessage(sendMsg);
  //   }
  // }, [sendMsg, isConnected]);

  const childRef = useRef();

  useEffect(() => {
    if (CardMessage) {
      let dataMsg :any= CardMessage;
      console.log('value=>', value);

      if (dataMsg.result == 0) {
        let [_, __, num] = useDetermineCardType(value);

        console.log('=====>', num);

        if (type == '挂失卡,读卡成功') {
          LossCard(dataMsg.cardid, dataMsg.cardclass);
          setLostcard(dataMsg.cardid);
        } else if (type == '退卡成功') {
          delLostCard(Lostcard);
          setLostcard('');
          message.success(intl.formatMessage({ id: 'ManageCards.return successful' }));
        } else {
          let data = {
            cardHolder: username,
            loassCardType: num,
            cardNum: dataMsg.cardid,
            expirationDate: sendMsg.endtime,
            exitTime: sendMsg.endtime,
            status: 1,
            cmdInfo: JSON.stringify(sendMsg),
          };
          AddlsockLog(data);
          message.success(intl.formatMessage({ id: 'ManageCards.Card issuance successful.' }));
          childRef.current?.reload();
        }

        form.resetFields();
      } else {
        message.error(CardMessage.msg);
      }
    }
  }, [CardMessage]);

  const [CardType, setcardType] = useState('');

  const onChange = (e: RadioChangeEvent) => {
    console.log('radio checked', e.target.value);
    setValue(e.target.value);
  };
  const [username, setusername] = useState('');
  const onFinish = async (values: any) => {
    setusername(values.username);
    let [_, __, num] = useDetermineCardType(values.leix);

    let result = await LostTimer({
      CardType: num,
    });
    if (result.code == 0) {
      const timeString = values.timer.$d;
      const date = dayjs(timeString);
      const formattedDate = date.format('YYYY-MM-DD HH:mm:ss');
      console.log(value); // guestcard
      setcardType(value);
      let data = {
        cardclass: 'losscard',
        uuid: value,
        roomid: '00000000',
        losstype: value == 'guestcard' ? '1' : '2',
        losscardclass: value,
        begintime: result.data.loss_expire_date,
        endtime: formattedDate,
        custontime: value == 'guestcard' ? '000' : result.data.manage_expire_date,
      };
      setsendMsg(data);
      let res = await Write_LossCard(data);

      setCardMessage(res);
      setType(`${value}挂失成功`);
    }
  };

  const [Lostcard, setLostcard] = useState('');
  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };
  const [useflag, setuseflag] = useState(false);
  const [useMsg, setuseMsg] = useState<CardMSg | any>();
  const [cardType] = useState(intl.formatMessage({ id: 'card.Report Lost card' }));
  const [Cardid, setCardid] = useState(''); // 传递卡号
  const LossCardAfter = async () => {
    // let data = { "cardclass": "readcard", "uuid": "12345", "isclear": "0" }
    // setsendMsg(data)

    let data = await Read_Card();
    if (data.msg == '空卡')
      return message.error(intl.formatMessage({ id: 'ManageCards.Empty card' }));
    setsendMsg(data);
    console.log('data', data);
    setCardMessage(data);
    setType('挂失卡,读卡成功');
  };
  const LossCard = async (card: string, type: string): Promise<any> => {
    if (type != 'losscard') {
      const [res] = useDetermineCardType(type);
      return message.error(intl.formatMessage({ id: 'Table.Return Room Card Loss' }, { card:res }));
    }
    setCardid(card);
    let data = await getLogLossCardCardNum(card);

    if (data.data.cardNum) {
      setuseMsg(data.data);
      setuseflag(true);
    }
  };
  const handleOkFlag = () => {
    setuseflag(false);
  };

  // const [ISchangeTimer, setISchangeTimer] = useState(false)
  // const changelostCard = (value: any) => {
  //   setISchangeTimer(value.target.checked)
  // }

  return (
    <>
      {useflag && (
        <AdminCardmodel
          useflag={useflag}
          useMsg={useMsg}
          cardType={cardType}
          handleOkFlag={handleOkFlag}
          setsendMsg={setsendMsg}
          setType={setType}
          Cardid={Cardid}
        />
      )}
      <Card title={intl.formatMessage({ id: 'Lost.Write lost card' })}>
        <div style={{ float: 'right', height: '23vh' }}>
          <Button type="primary" danger onClick={LossCardAfter}>
            {intl.formatMessage({ id: 'Lost.Return card' })}
          </Button>
        </div>
        <Form
          name="basic"
          labelCol={{ span: 3 }}
          wrapperCol={{ span: 16 }}
          style={{ minWidth: 600 }}
          initialValues={{ remember: true }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
          form={form}
        >
          <Form.Item<any>
            label={intl.formatMessage({ id: 'Lost.Card type' })}
            name="leix"
            rules={[
              {
                required: true,
                message: intl.formatMessage({ id: 'Lost.Please select card type' }),
              },
            ]}
          >
            <Radio.Group onChange={onChange} value={value} style={{ width: '650px' }}>
              {/* <Radio value={'guestcard'}>房卡</Radio> */}
              <Radio value={'mastercard'}>{intl.formatMessage({ id: 'card.Total card' })}</Radio>
              <Radio value={'buildingcard'}>
                {intl.formatMessage({ id: 'card.Building card' })}
              </Radio>
              <Radio value={'floorcard'}>
                {intl.formatMessage({ id: 'card.Layer control card' })}
              </Radio>
              <Radio value={'emergencycard'}>
                {intl.formatMessage({ id: 'card.Emergency card' })}
              </Radio>
              <Radio value={'staffcard'}>{intl.formatMessage({ id: 'card.Hygiene card' })}</Radio>
              <Radio value={'alwaysopencard'}>
                {intl.formatMessage({ id: 'card.Always-on card' })}
              </Radio>
              <Radio value={'setvipcard'}>
                {intl.formatMessage({ id: 'card.Authorization card' })}
              </Radio>
              <Radio value={'personnelcard'}>
                {intl.formatMessage({ id: 'card.Employee card' })}
              </Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item<any>
            label={intl.formatMessage({ id: "ManageCards.Cardholder's name" })}
            name="username"
            rules={[{ required: true, message: intl.formatMessage({ id: 'Lost.Enter name' }) }]}
          >
            <Input
              style={{ width: '300px' }}
              placeholder={intl.formatMessage({ id: 'Table.cardholder' })}
            />
          </Form.Item>
          <Form.Item<any>
            label={intl.formatMessage({ id: 'Lost.Expiration date' })}
            name="timer"
            rules={[
              {
                required: true,
                message: intl.formatMessage({ id: 'Lost.select Expiration date' }),
              },
            ]}
            initialValue={checkIntimer}
          >
            <DatePicker showTime format="YYYY-MM-DD HH:mm:ss" style={{ width: '300px' }} />
          </Form.Item>
          {/* <Form.Item label="选项" name="excludeNumber2">
            <Checkbox.Group value={excludeNumber2}>
              <Checkbox value="单独" onChange={changelostCard}>
                <span style={{ color: '#D4D4D4' }}>
                  挂失已发卡(勾选此选项的发的管理卡，需要将卡在锁上刷一下后，挂失作用才生效)
                </span>
              </Checkbox>
              &emsp;
            </Checkbox.Group>
          </Form.Item> */}
          <Form.Item wrapperCol={{ offset: 3, span: 16 }}>
            <Button type="primary" htmlType="submit">
              {intl.formatMessage({ id: 'Lost.Write cards' })}
            </Button>
          </Form.Item>
        </Form>
        <div>
          <LostCardTable ref={childRef} setsendMsg={setsendMsg} setType={setType} value={value} />
        </div>
      </Card>
    </>
  );
};

export default index;
